package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 订单服务模块
 */

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderDetailsMapper orderDetailsMapper;
    
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketServer webSocketServer;
    
    /**
     * 用户提交订单
     * @param orderDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO orderDTO) {
        // 先查询用户订单提交的地址是否合适
        AddressBook addressBook = addressBookMapper.getById(orderDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 在查询用户此时购物车是否为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart cart = new ShoppingCart();
        cart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(cart);
        if(list == null ||list.size() == 0)
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        // 在表里添加订单信息
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderDTO, orders);
        // 设置订单时间
        orders.setOrderTime(LocalDateTime.now());
        // 设置订单支付状态
        orders.setPayStatus(Orders.UN_PAID);
        // 设置订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        // 设置订单号，使用系统时间戳
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        // 设置订单主人电话号
        orders.setPhone(addressBook.getPhone());
        // 设置收货人姓名
        orders.setConsignee(addressBook.getConsignee());
        // 设置这单订单的用户ID
        orders.setUserId(userId);
        // 设置详细地址
        orders.setAddress(addressBook.getDetail());
        orderMapper.insert(orders);
        // 在添加订单明细表
        List<OrderDetail> listOrderDetail = new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            listOrderDetail.add(orderDetail);
        }
        log.info("订单明细表数据：{}",listOrderDetail);
        orderDetailsMapper.insertBeach(listOrderDetail);
        //封装OrderVO对象
        OrderSubmitVO build = OrderSubmitVO.builder()
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .id(userId)
                .build();
        // 清空购物车
        shoppingCartMapper.delete(cart);
        // 返回数据
        
        return build;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改

        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付

        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单


        //发现没有将支付时间 check_out属性赋值，所以在这里更新

        LocalDateTime checkoutTime = LocalDateTime.now();

        Orders ordersDB = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        Long orderId = ordersDB.getId();

        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, checkoutTime, orderId);
        HashMap map = new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号: "+ ordersDB.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 历史订单分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    @Transactional
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 获取 当前用户的ID
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 通过当前用户的ID 查询出当前用户的所有订单
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 通过当前用户的所有订单ID 查询出用户订单的明细
        List<OrderVO> list = new ArrayList<>();
        if(page != null && page.size() > 0){
            for (Orders orders : page) {
                OrderVO orderVO = new OrderVO();
                Long orderId = orders.getId();
                List<OrderDetail> orderDetails = orderDetailsMapper.getByOrderId(orderId);
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(), list);
    }

    /**
     * 根据订单ID查询订单
     * @param id
     * @return
     */
    @Override
    @Transactional
    public OrderVO details(long id) {
        // 根据订单ID查询订单信息
        Orders orders = orderMapper.getById(id);
        // 根据订单
        List<OrderDetail> details = orderDetailsMapper.getByOrderId(id);
        // 封装数据
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(details);
        return orderVO;
    }

    /**
     * 根据订单Id 取消订单
     * @param id
     */
    @Transactional
    public void userCancelById(long id) {
        // 查询订单
        Orders order = orderMapper.getById(id);

        // 校验订单是否存在
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (order.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 如果支付了就修改 支付状态
        if(order.getStatus() == 2){
            order.setPayStatus(2);
        }

        // 如果没有支付就修改一下订单整体的状态
        order.setStatus(6);
        order.setCancelReason("用户取消");
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 根据 订单Id 把购物车内容重新放入购物车
     * @param id
     */
    @Override
    @Transactional
    public void repetition(long id) {
        List<OrderDetail> details = orderDetailsMapper.getByOrderId(id);
        // 查到 用户Id
        Long userId = BaseContext.getCurrentId();
        // 封装数据
        List<ShoppingCart> list = new ArrayList<>();
        for (OrderDetail detail : details) {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(detail,cart,"id");
            cart.setUserId(userId);
            list.add(cart);
        }
        // 批量插入
       shoppingCartMapper.insertBeach(list);
    }

    /**
     * 管理端分页查询订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单需要返回菜品详细信息
        List<OrderVO> list = getOrderVOList(page);
        return new PageResult(page.getTotal(),list);
    }

    /**
     * 有的订单需要返回菜品详细信息
     * @param page
     * @return
     */
    private  List<OrderVO> getOrderVOList(Page<Orders> page){
        List<OrderVO> list = new ArrayList<>();
        List<Orders> orders = page.getResult();
        if(orders != null&& orders.size() > 0){
            for (Orders order : orders) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order,orderVO);

                String caipin = getOrderDishesStr(order);

                orderVO.setOrderDishes(caipin);
                list.add(orderVO);
            }
        }
        return list;
    }

    /**
     * 根据订单把订单对应的详细菜品 转换成字符串
     * @param order
     * @return
     */
    private  String getOrderDishesStr(Orders order){
        String str = "";
        List<OrderDetail> details = orderDetailsMapper.getByOrderId(order.getId());

        for (OrderDetail detail : details) {
            String name = detail.getName();
            str += name;
            Integer number = detail.getNumber();
            str += "*" + number + ";";
        }
        return str;
    }

    /**
     * 查询出订单的各个状态的数量
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 封装数据返回给前端
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 接单 也就是修改一下订单状态
     */
    @Override
    public void confirm(OrdersConfirmDTO orderConfirmDTO) {
        Orders build = Orders.builder()
                .id(orderConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        // 修改订单状态
        orderMapper.update(build);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 先查询订单
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        // 如果订单为空 或者订单状态不是待接单是无法拒单的
        if(orders == null && orders.getStatus() == Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 修改订单状态
        orders.setPayStatus(Orders.REFUND);
        // 修改一下订单信息 订单状态、拒单原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 取消订单 如果此时用户已经付款了 则退款
     * @param ordersCancelDTO
     */
    @Override
    @Transactional
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());

        // 如果支付了 则修改支付状态
        if(orders.getPayStatus()== Orders.PAID)
            orders.setPayStatus(Orders.REFUND);

        // 修改订单状态 取消时间 订单状态 取消理由
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(orders);
    }

    /**
     * 派送订单 就是将订单为待派送 的订单状态改为派送中
     * @param id
     */
    @Transactional
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);
        if(orders == null || orders.getStatus() != Orders.CONFIRMED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        // 修改订单状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单 就是将状态为已派送的订单状态改为已完成 还有完成的时间也要设置
     * @param id
     */
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);

        if(orders == null || orders.getStatus() != Orders.DELIVERY_IN_PROGRESS)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);

    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(long id) {
        Orders orderDB = orderMapper.getById(id);

        if(orderDB == null || orderDB.getStatus() != Orders.TO_BE_CONFIRMED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);


        HashMap map = new HashMap();
        map.put("type",2);
        map.put("orderId",orderDB.getId());
        map.put("content","订单号: "+ orderDB.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }
}
